import os

def rename_images():
    folder_path = input("请输入要处理的文件夹路径: ")
    image_files = []
    # 存储文件名对应的数字
    file_numbers = {}
    for filename in os.listdir(folder_path):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            try:
                number = int(os.path.splitext(filename)[0])
                image_files.append(filename)
                file_numbers[filename] = number
            except ValueError:
                image_files.append(filename)

    # 按数字排序，非数字文件名排到最后
    sorted_files = sorted(image_files, key=lambda x: file_numbers.get(x, float('inf')))
    used_numbers = set()
    next_number = 1
    for filename in sorted_files:
        ext = os.path.splitext(filename)[1]
        while next_number in used_numbers:
            next_number += 1
        new_name = f"{next_number}{ext}"
        old_path = os.path.join(folder_path, filename)
        new_path = os.path.join(folder_path, new_name)
        os.rename(old_path, new_path)
        print(f"Renamed {filename} to {new_name}")
        used_numbers.add(next_number)
        next_number += 1

if __name__ == "__main__":
    rename_images()
